package com.xsprite.managesys.service;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.extractor.XSSFExcelExtractor;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.xsprite.managesys.bean.DataCell;
import com.xsprite.managesys.bean.DataRow;
import com.xsprite.managesys.bean.MySheet;
import com.xsprite.managesys.bean.XlsxFileBean;
import com.xsprite.managesys.log.LogManager;

public class XlsxFileManager {
	
	private static XlsxFileManager instance;
	
	public static XlsxFileManager getInstance(){
		if(instance == null){
			instance = new XlsxFileManager();
		}
		return instance;
	}
	
	private List<XlsxFileBean> fileBeans;
	
	private XlsxFileBean itemsBean;
	
	private Map<Integer, List<String>> itemsMap = new HashMap<Integer, List<String>>();
	
	public String getItemById(int id){
		List<String> names = itemsMap.get(id);
		if(names == null){
			return null;
		}
		StringBuffer sb = new StringBuffer();
		for(String name : names){
			sb.append(name);
		}
		return sb.toString();
	}
	
	private XlsxFileManager(){
		fileBeans = new ArrayList<XlsxFileBean>();
	}
	
	private int hasBean(XlsxFileBean bean){
		for(int i = 0; i < fileBeans.size(); i++){
			if(fileBeans.get(i).getFilename().equals(bean.getFilename())){
				return i;
			}
		}
		return -1;
	}
	
	public void addBean(XlsxFileBean bean){
		int index = hasBean(bean);
		if(index != -1){
			fileBeans.remove(index);
		}
		fileBeans.add(bean);
	}
	
	public List<XlsxFileBean> getBeans(){
		return fileBeans;
	}
	
	public void deleteFile(String id, String userid){
		for(XlsxFileBean bean : fileBeans){
			if(bean.getId().equals(id)){
				File file = new File(bean.getFilePath());
				boolean isSuccess = FileUtils.deleteQuietly(file);
				if(isSuccess){
					fileBeans.remove(bean);
					LogManager.getInstance().log4j("userid = " + userid + " 删除文件" + id + "--" + bean.getFilename() + "成功");
				} else {
					LogManager.getInstance().log4j("userid = " + userid + "删除文件" + id + "--" + bean.getFilename() + "失败(apache common io)");
				}
				break;
			}
		}
	}
	
	public boolean hasFile(String id){
		for(XlsxFileBean bean : fileBeans){
			if(bean.getId().equals(id)){
				return true;
			}
		}
		return false;
	}
	
	public List<XlsxFileBean> getBeansByIds(List<String> ids){
		List<XlsxFileBean> result = new ArrayList<XlsxFileBean>();
		Map<String, XlsxFileBean> tempMap = new HashMap<String, XlsxFileBean>();
		for(XlsxFileBean bean : fileBeans){
			tempMap.put(bean.getId(), bean);
		}
		for(String id : ids){
			if(tempMap.containsKey(id)){
				result.add(tempMap.get(id));
			} else {
				throw new RuntimeException("找不到文件bean: id = " + id);
			}
		}
		return result;
	}
	
	public void clearBeans(){
		fileBeans.clear();
	}
	
	public void reloadExcelDatas() throws Exception{
		List<XlsxFileBean> beans = XlsxFileManager.getInstance().getBeans();
		for(XlsxFileBean bean : beans){
			readExcelFile(bean.getFilePath(), bean);
		}
	}
	
	public void readItemExcelFile(String excelPath, XlsxFileBean bean)  throws Exception{
		File excelFile = new File(excelPath);
		FileInputStream is = new FileInputStream(excelFile);
		Workbook wb = null;
		String fileName = excelFile.getName();
		String hz = fileName.substring(fileName.lastIndexOf("."), fileName.length());
		org.apache.poi.ss.extractor.ExcelExtractor extractor = null;
		if (hz.equals(".xls")) {
			wb = new HSSFWorkbook(new POIFSFileSystem(is));
			extractor = new org.apache.poi.hssf.extractor.ExcelExtractor((HSSFWorkbook) wb);
		} else {
			wb = new XSSFWorkbook(is);
			extractor = new XSSFExcelExtractor((XSSFWorkbook) wb);
		}
		List<MySheet> mysheets = new ArrayList<MySheet>();
		for(int k = 0; k < 2; k++){
			Sheet theSheet = wb.getSheetAt(k);
			String sheetName = wb.getSheetName(k);
			List<DataRow> dataRows = new ArrayList<DataRow>();
			MySheet mySheet = new MySheet(sheetName, dataRows);
			mysheets.add(mySheet);
//			getExcelDatas().put(sheetName, dataRows);
//			List<String> sheets = new ArrayList<String>();
//			sheets.add(sheetName);
//			getFileNameAndSheetNamesMap().put(fileName, sheets);
			Row commentsRow = theSheet.getRow(0);
			Row fieldRow = theSheet.getRow(1);
			Row typeRow = theSheet.getRow(2);
			Row dataTypeRow = theSheet.getRow(3);
			int rowLen = theSheet.getLastRowNum();
			for (int i = 4; i <= rowLen; i++) {
				Row dataRow = theSheet.getRow(i);
				int dataCellNum = dataRow.getLastCellNum();
				DataRow dRow = new DataRow();
//				dRow.setRowId((int) dataRow.getCell(0).getNumericCellValue());
				dRow.setDataCells(new ArrayList<DataCell>());
				dataRows.add(dRow);
				for (int j = 0; j < dataCellNum; j++) {
					DataCell dataCell = new DataCell();
//					dataCell.setName(fieldRow.getCell(j).getStringCellValue());
//					dataCell.setText(commentsRow.getCell(j).getStringCellValue());
//					Cell typeCell = typeRow.getCell(j);
//					if (typeCell.getCellType() != 0) {
//						throw new RuntimeException("类型列只能为数字@row: " + i + ",column " + j);
//					}
//					dataCell.setType((int) typeCell.getNumericCellValue());
//					Cell dataTypeCell = dataTypeRow.getCell(j);
//					if (dataTypeCell.getCellType() != 0) {
//						throw new RuntimeException("类型列只能为数字@row: " + i + ", column " + j);
//					}
//					dataCell.setDataType((int) dataTypeCell.getNumericCellValue());
					Cell cell = dataRow.getCell(j);
					if (cell != null) {
						switch (cell.getCellType()) {
						case 0:
							dataCell.setValue(Integer.valueOf((int) cell.getNumericCellValue()));
							break;
						case 1:
							dataCell.setValue(cell.getStringCellValue());
							break;
						case 4:
							dataCell.setValue(Boolean.valueOf(cell.getBooleanCellValue()));
							break;
						case 2:
							dataCell.setValue(cell.getStringCellValue());
							break;
						case 3:
							dataCell.setValue("");
							break;
						case 5:
							throw new RuntimeException("数据类型错误@row: " + i + ", column: " + j);
						default:
							throw new RuntimeException("数据类型错误@row: " + i + ", column: " + j);
						}
						dRow.getDataCells().add(dataCell);
					} else {
						throw new RuntimeException("单元格为空@row: " + i + ", column: " + j);
					}
				}
			}
		}
		bean.setSheets(mysheets);
	}
	
	public void readExcelFile(String excelPath, XlsxFileBean bean) throws Exception{
			File excelFile = new File(excelPath);
			FileInputStream is = new FileInputStream(excelFile);
			Workbook wb = null;
			String fileName = excelFile.getName();
			String hz = fileName.substring(fileName.lastIndexOf("."), fileName.length());
			org.apache.poi.ss.extractor.ExcelExtractor extractor = null;
			if (hz.equals(".xls")) {
				wb = new HSSFWorkbook(new POIFSFileSystem(is));
				extractor = new org.apache.poi.hssf.extractor.ExcelExtractor((HSSFWorkbook) wb);
			} else {
				wb = new XSSFWorkbook(is);
				extractor = new XSSFExcelExtractor((XSSFWorkbook) wb);
			}
			Sheet theSheet = wb.getSheetAt(0);
			String sheetName = wb.getSheetName(0);
			List<DataRow> dataRows = new ArrayList<DataRow>();
			List<MySheet> mysheets = new ArrayList<MySheet>();
			MySheet mySheet = new MySheet(sheetName, dataRows);
			mysheets.add(mySheet);
			bean.setSheets(mysheets);
//			getExcelDatas().put(sheetName, dataRows);
//			List<String> sheets = new ArrayList<String>();
//			sheets.add(sheetName);
//			getFileNameAndSheetNamesMap().put(fileName, sheets);
			Row commentsRow = theSheet.getRow(0);
			Row fieldRow = theSheet.getRow(1);
			Row typeRow = theSheet.getRow(2);
			Row dataTypeRow = theSheet.getRow(3);
			int rowLen = theSheet.getLastRowNum();
			for (int i = 4; i <= rowLen; i++) {
				Row dataRow = theSheet.getRow(i);
				int dataCellNum = dataRow.getLastCellNum();
				DataRow dRow = new DataRow();
				dRow.setRowId((int) dataRow.getCell(0).getNumericCellValue());
				dRow.setDataCells(new ArrayList<DataCell>());
				dataRows.add(dRow);
				System.out.println();
				for (int j = 0; j < dataCellNum; j++) {
					DataCell dataCell = new DataCell();
					dataCell.setName(fieldRow.getCell(j).getStringCellValue());
					dataCell.setText(commentsRow.getCell(j).getStringCellValue());
					Cell typeCell = typeRow.getCell(j);
					if (typeCell.getCellType() != 0) {
						throw new RuntimeException("类型列只能为数字@row: " + i + ",column " + j);
					}
					dataCell.setType((int) typeCell.getNumericCellValue());
					Cell dataTypeCell = dataTypeRow.getCell(j);
					if (dataTypeCell.getCellType() != 0) {
						throw new RuntimeException("类型列只能为数字@row: " + i + ", column " + j);
					}
					dataCell.setDataType((int) dataTypeCell.getNumericCellValue());
					Cell cell = dataRow.getCell(j);
					if (cell != null) {
						switch (cell.getCellType()) {
						case 0:
							dataCell.setValue(Integer.valueOf((int) cell.getNumericCellValue()));
							break;
						case 1:
							dataCell.setValue(cell.getStringCellValue());
							break;
						case 4:
							dataCell.setValue(Boolean.valueOf(cell.getBooleanCellValue()));
							break;
						case 2:
							dataCell.setValue(cell.getStringCellValue());
							break;
						case 3:
							dataCell.setValue("");
							break;
						case 5:
							throw new RuntimeException("数据类型错误@row: " + i + ", column: " + j);
						default:
							throw new RuntimeException("数据类型错误@row: " + i + ", column: " + j);
						}
						dRow.getDataCells().add(dataCell);
					} else {
						throw new RuntimeException("单元格为空@row: " + i + ", column: " + j);
					}
				}
			}
	}

	public void loadItemsMap(){
		String toloadSheets = "道具装备";
		for(MySheet sheet : itemsBean.getSheets()){
			if(!toloadSheets.contains(sheet.getSheetName())){
				continue;
			}
			List<DataRow> rows = sheet.getRows();
			for(DataRow row : rows){
				String sidStr = row.getDataCells().get(1).getValue().toString();
				int sid = Integer.parseInt(sidStr);
				List<String> tempList = itemsMap.get(sid);
				if(tempList == null){
					tempList = new ArrayList<String>();
					itemsMap.put(sid, tempList);
				}
				tempList.add(row.getDataCells().get(0).getValue().toString());
			}
		}
	}
	
	public XlsxFileBean getItemsBean() {
		return itemsBean;
	}

	public void setItemsBean(XlsxFileBean itemsBean) {
		this.itemsBean = itemsBean;
	}
}
